<template lang="pug">
.view.cp-manage-approve.fix-flex-pos
  //- 查询
  el-form.ae-search(:inline="true")
    el-form-item(label="审批类型 : ")
      el-select(v-model="appType", placeholder="请选择", style="width: 120px")
        el-option(
          v-for="item in typeSelectAll",
          :key="item.value", :label="item.name",
          :value="item.value")
    el-form-item(label="状态 : ")
      el-select(v-model="appStatus", placeholder="请选择", style="width: 120px")
        el-option(
          v-for="item in statusSelectAll",
          :key="item.value", :label="item.name",
          :value="item.value")
    el-form-item(label="创建人 : ")
      el-select(v-model="appCreator", placeholder="请选择", style="width: 120px")
        el-option(
          v-for="item in empSelectAll",
          :key="item.value", :label="item.name",
          :value="item.value")
    el-form-item
      el-button(type="primary", @click="searchApproves") 搜索
    el-form-item
      el-button(type="primary", @click="resetSearch", plain) 重置
    el-form-item
      el-button(type="primary", @click="addApprove") 新建审批流程
  //- 列表
  .ae-table
    el-table(
      :data="approveList",
      highlight-current-row
      height="100%"
      size="mini"
      v-loading="loadingApproves")
      el-table-column(align="center", show-overflow-tooltip, type="index", :index="indexMethod", label="序号", :fixed="true")
      el-table-column(align="center", show-overflow-tooltip, prop="type", label="审批类型")
        template(slot-scope="scope")
          span {{ scope.row.type | compare-list(typeSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="status", label="状态")
        template(slot-scope="scope")
          span {{ scope.row.status | compare-list(statusSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="createUser", label="创建人")
        template(slot-scope="scope")
          span {{ scope.row.createUser | compare-list(empSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="createTime", label="创建时间")
        template(slot-scope="scope")
          span {{ scope.row.createTime | date-format }}
      el-table-column(align="center", show-overflow-tooltip, prop="endorses", label="审批人")
      el-table-column(align="center", show-overflow-tooltip, prop="remark", label="备注")
      el-table-column(align="center", label="操作", min-width="90px")
        template(slot-scope="scope")
          el-tooltip(content="查看")
            i.icon-act.el-icon-view(@click="viewApprove(scope.row)")
          el-tooltip(content="编辑")
            i.icon-act.el-icon-edit(@click="eidtApprove(scope.row, scope.$index)")
          el-tooltip(content="删除", :disabled="scope.row.status == '0'")
            i.icon-act.el-icon-delete(@click="deleteApprove(scope.row, scope.$index)", :class="{disabled: scope.row.status == '0'}")
  //- 分页
  el-pagination.ae-pagination(
    layout="total, prev, pager, next, jumper",
    @current-change="changeApprovePage",
    :current-page.sync="currentPage",
    :page-size="pageSize",
    :total="approveListTotal")
  el-dialog.ae-dialog(
    :title="dialogTitle",
    :close-on-click-modal="viewStatus",
    :visible.sync="showDialog")
    .ae-pop-show(v-show="viewStatus")
      el-row(:gutter="20")
        el-col(:span="12")
          strong 【 审批类型 】
          span {{ popupObj.type | compare-list(typeSelect) }}
        el-col(:span="12")
          strong 【 状态 】
          span {{ popupObj.status | compare-list(statusSelect) }}
      el-row(:gutter="20")
        el-col(:span="12")
          strong 【 创建人 】
          span {{ popupObj.createUser | compare-list(empSelect) || '未知' }}
      el-row(:gutter="20")
        el-col(:span="24")
          strong 【 一级审批 】
          span(v-show="popupObj.endorserTypeLevel1==0") {{ popupObj.endorserLevel1 | compare-list(buyerSelect) }}
          span(v-show="popupObj.endorserTypeLevel1==1") 二级部门主管
          span(v-show="popupObj.endorserTypeLevel1==2") 一级部门主管
          span(v-show="popupObj.endorserTypeLevel1==3") 公司主管
      el-row(:gutter="20", v-show="typeof(popupObj.endorserTypeLevel2) == 'number'")
        el-col(:span="24")
          strong 【 二级审批 】
          span(v-show="popupObj.endorserTypeLevel2==0") {{ popupObj.endorserLevel2 | compare-list(buyerSelect) }}
          span(v-show="popupObj.endorserTypeLevel2==1") 二级部门主管
          span(v-show="popupObj.endorserTypeLevel2==2") 一级部门主管
          span(v-show="popupObj.endorserTypeLevel2==3") 公司主管
      el-row(:gutter="20", v-show="typeof(popupObj.endorserTypeLevel3) == 'number'")
        el-col(:span="24")
          strong 【 三级审批 】
          span(v-show="popupObj.endorserTypeLevel3==0") {{ popupObj.endorserLevel3 | compare-list(buyerSelect) }}
          span(v-show="popupObj.endorserTypeLevel3==1") 二级部门主管
          span(v-show="popupObj.endorserTypeLevel3==2") 一级部门主管
          span(v-show="popupObj.endorserTypeLevel3==3") 公司主管
      el-row(:gutter="20", v-show="typeof(popupObj.endorserTypeLevel4) == 'number'")
        el-col(:span="24")
          strong 【 四级审批 】
          span(v-show="popupObj.endorserTypeLevel4==0") {{ popupObj.endorserLevel4 | compare-list(buyerSelect) }}
          span(v-show="popupObj.endorserTypeLevel4==1") 二级部门主管
          span(v-show="popupObj.endorserTypeLevel4==2") 一级部门主管
          span(v-show="popupObj.endorserTypeLevel4==3") 公司主管
      el-row(:gutter="20", v-show="typeof(popupObj.endorserTypeLevel5) == 'number'")
        el-col(:span="24")
          strong 【 五级审批 】
          span(v-show="popupObj.endorserTypeLevel5==0") {{ popupObj.endorserLevel5 | compare-list(buyerSelect) }}
          span(v-show="popupObj.endorserTypeLevel5==1") 二级部门主管
          span(v-show="popupObj.endorserTypeLevel5==2") 一级部门主管
          span(v-show="popupObj.endorserTypeLevel5==3") 公司主管
      el-row(:gutter="20")
        el-col(:span="24")
          strong 【 备注 】
          span {{ popupObj.remark || '暂无' }}
    .ae-pop-wrap(v-show="!viewStatus")
      el-form.ae-pop-form(:inline="true", label-width="72px")
        el-row(:gutter="36")
          el-col(:span="12")
            el-form-item.is-required(label="审批类型")
              el-select(v-model="popupObj.type", :disabled="!!popupObj.id")
                el-option(
                  v-for="item in typeSelect",
                  :key="item.value", :label="item.name",
                  :value="item.value")
          el-col(:span="12")
            el-form-item.is-required.special-label(label="状态")
              el-select(v-model="popupObj.status", placeholder="请选择")
                el-option(
                  v-for="item in statusSelect",
                  :key="item.value", :label="item.name",
                  :value="item.value")
        el-row.ae-approve-row
          el-col(:span="24")
            span.span-required(style="display: inline-block; width: 72px") 一级审批
            el-radio(v-model="popupObj.endorserTypeLevel1", :label="0") 指定员工
            el-select(v-model="popupObj.endorserLevel1", placeholder="请选择", style="width: 128px; marginLeft: 8px; marginRight: 32px")
              el-option(v-for="item in buyerSelect", :key="item.value", :label="item.name", :value="item.value")
            el-radio(v-model="popupObj.endorserTypeLevel1", :label="1") 二级部门主管
            el-radio(v-model="popupObj.endorserTypeLevel1", :label="2") 一级部门主管
            el-radio(v-model="popupObj.endorserTypeLevel1", :label="3") 公司主管
        el-row.ae-approve-row(v-show="endorsesIndex > 1")
          el-col(:span="24")
            span(style="display: inline-block; width: 72px") 二级审批
            el-radio(v-model="popupObj.endorserTypeLevel2", :label="0") 指定员工
            el-select(v-model="popupObj.endorserLevel2", placeholder="请选择", style="width: 128px; marginLeft: 8px; marginRight: 32px")
              el-option(v-for="item in buyerSelect", :key="item.value", :label="item.name", :value="item.value")
            el-radio(v-model="popupObj.endorserTypeLevel2", :label="1") 二级部门主管
            el-radio(v-model="popupObj.endorserTypeLevel2", :label="2") 一级部门主管
            el-radio(v-model="popupObj.endorserTypeLevel2", :label="3") 公司主管
        el-row.ae-approve-row(v-show="endorsesIndex > 2")
          el-col(:span="24")
            span(style="display: inline-block; width: 72px") 三级审批
            el-radio(v-model="popupObj.endorserTypeLevel3", :label="0") 指定员工
            el-select(v-model="popupObj.endorserLevel3", placeholder="请选择", style="width: 128px; marginLeft: 8px; marginRight: 32px")
              el-option(v-for="item in buyerSelect", :key="item.value", :label="item.name", :value="item.value")
            el-radio(v-model="popupObj.endorserTypeLevel3", :label="1") 二级部门主管
            el-radio(v-model="popupObj.endorserTypeLevel3", :label="2") 一级部门主管
            el-radio(v-model="popupObj.endorserTypeLevel3", :label="3") 公司主管
        el-row.ae-approve-row(v-show="endorsesIndex > 3")
          el-col(:span="24")
            span(style="display: inline-block; width: 72px") 四级审批
            el-radio(v-model="popupObj.endorserTypeLevel4", :label="0") 指定员工
            el-select(v-model="popupObj.endorserLevel4", placeholder="请选择", style="width: 128px; marginLeft: 8px; marginRight: 32px")
              el-option(v-for="item in buyerSelect", :key="item.value", :label="item.name", :value="item.value")
            el-radio(v-model="popupObj.endorserTypeLevel4", :label="1") 二级部门主管
            el-radio(v-model="popupObj.endorserTypeLevel4", :label="2") 一级部门主管
            el-radio(v-model="popupObj.endorserTypeLevel4", :label="3") 公司主管
        el-row.ae-approve-row(v-show="endorsesIndex > 4")
          el-col(:span="24")
            span(style="display: inline-block; width: 72px") 五级审批
            el-radio(v-model="popupObj.endorserTypeLevel5", :label="0") 指定员工
            el-select(v-model="popupObj.endorserLevel5", placeholder="请选择", style="width: 128px; marginLeft: 8px; marginRight: 32px")
              el-option(v-for="item in buyerSelect", :key="item.value", :label="item.name", :value="item.value")
            el-radio(v-model="popupObj.endorserTypeLevel5", :label="1") 二级部门主管
            el-radio(v-model="popupObj.endorserTypeLevel5", :label="2") 一级部门主管
            el-radio(v-model="popupObj.endorserTypeLevel5", :label="3") 公司主管
        el-button.ae-approve-add(type="primary", @click="addEndorser") 新增审批
        el-button.ae-approve-reset(type="primary", @click="resetEndorser", plain) 重置审批
        el-row
          el-col(:span="24")
            el-form-item(label="备注")
              el-input(v-model="popupObj.remark")
    el-row(v-show="!viewStatus")
      el-col(:span="24", style="text-align: center;")
         el-button(type="primary", style="width: 80px;", plain, @click="closeDialog") 取消
         el-button(type="primary", style="width: 80px; margin-left: 40px;", @click="saveApprove") 确定
</template>

<script>
import { mapGetters } from 'vuex';
import ComApi from '@/api/common';
import ManApi from '@/api/manage';
import check from './check';

export default {
  name: 'manapprove',
  data() {
    return {
      // search
      appType: null,
      appStatus: null,
      appCreator: null,
      // table
      approveList: [],
      approveListTotal: 1,
      loadingApproves: true,
      currentPage: 1,
      pageSize: 20,
      // 弹层
      showDialog: false,
      dialogTitle: '新建审批流程',
      viewStatus: true,
      popupObj: {},
      // select list
      typeSelect: [],
      typeSelectAll: [],
      buyerSelect: [],
      statusSelect: [
        { name: '启用', value: '0' },
        { name: '禁用', value: '1' }
      ],
      statusSelectAll: [
        { name: '全部', value: null },
        { name: '启用', value: '0' },
        { name: '禁用', value: '1' }
      ],
      endorsesIndex: 1
    };
  },
  computed: {
    ...mapGetters(['empSelect', 'empSelectAll', 'employeeId'])
  },
  methods: {
    indexMethod (i) {
      const size = this.pageSize || 20;
      return ((this.currentPage - 1) * size) + (i + 1);
    },
    openDialog () {
      this.showDialog = true;
    },
    closeDialog () {
      this.showDialog = false;
    },
    addEndorser () {
      if (this.endorsesIndex >= 5) {
        this.$message.info('至多允许五层审批链');
      } else {
        this.endorsesIndex += 1;
      }
    },
    resetEndorser () {
      for (let i = 1; i < 6; i++) {
        this.popupObj[`endorserTypeLevel${i}`] = '';
      }
      this.endorsesIndex = 1;
    },
    resetSearch () {
      this.appType = null;
      this.appStatus = null;
      this.appCreator = null;
    },
    makeSearch () {
      const params = {};
      if (typeof this.appType !== 'object') {
        params.type = this.appType;
      }
      if (typeof this.appStatus !== 'object') {
        params.status = this.appStatus;
      }
      if (typeof this.appCreator !== 'object') {
        params.createUser = this.appCreator;
      }

      return params;
    },
    searchApproves () {
      const params = this.makeSearch();
      this.loadingApproves = true;
      ManApi.getApproveList(params).then((result) => {
        if (!result.status) {
          this.approveList = result.obj.records;
          this.approveListTotal = result.obj.totalNum;
          this.currentPage = 1;
        } else {
          this.$message.error(result.comment);
          this.approveList = [];
          this.approveListTotal = 1;
          this.currentPage = 1;
        }
        this.loadingApproves = false;
      }).catch((error) => {
        this.loadingApproves = false;
        console.log(JSON.stringify(error));
      });
    },
    // 监听对Approve条目操作事件
    addApprove () {
      this.dialogTitle = '新建审批流程';
      this.viewStatus = false;
      this.popupObj = {};
      this.endorsesIndex = 1;
      this.openDialog();
    },
    viewApprove (row) {
      this.viewStatus = true;
      this.dialogTitle = '查看审批';
      ManApi.getApproveDetail({ id: row.id }).then((result) => {
        if (!result.status) {
          this.popupObj = result.obj;
          this.openDialog();
        } else {
          this.$message.error(result.comment);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    eidtApprove (row, index) {
      this.focusIndex = index;
      this.viewStatus = false;
      this.dialogTitle = '编辑审批';
      ManApi.getApproveDetail({ id: row.id }).then((result) => {
        if (!result.status) {
          this.popupObj = result.obj;
          this.endorsesIndex = 1;
          for (let i = 2; i < 6; i++) {
            if (typeof (this.popupObj[`endorserTypeLevel${i}`]) === 'number') {
              this.endorsesIndex += 1;
            }
          }
          this.openDialog();
        } else {
          this.$message.error(result.comment);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    deleteApprove (row, index) {
      // 启用时不能删除
      if (row.status == '0') {
        return;
      }
      this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loadingApproves = true;
        ManApi.deleteApprove({ id: row.id }).then((result) => {
          this.loadingApproves = false;
          if (!result.status) {
            this.approveList.splice(index, 1);
            this.approveListTotal = this.approveListTotal - 1;
            this.$message.success('删除成功');
          } else {
            this.$message.error(`删除失败：${result.comment}`);
          }
        }).catch((error) => {
          console.log(JSON.stringify(error));
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    saveApprove () {
      const canSave = check(this.popupObj, this.modifyPass);
      if (canSave) {
        this.popupObj.createUser = this.employeeId;
        ManApi.saveApprove(this.popupObj).then((result) => {
          if (!result.status) {
            let message = '保存成功';
            if (this.popupObj.id) {
              message = '修改成功';
              this.$set(this.approveList, this.focusIndex, result.obj);
            } else {
              this.approveList.unshift({});
              this.$set(this.approveList, 0, result.obj);
              this.approveListTotal += 1;
              if (this.approveListTotal > 20) {
                this.approveList.pop();
              }
            }
            this.$message.success(message);

            // 同类型下只能启用一种审批
            const type = this.popupObj.type;
            const status = this.popupObj.status;
            const id = this.popupObj.id || result.obj.id;
            if (status === '0') { // 如果改为启用状态，其他为禁用状态
              this.approveList.forEach((approve) => {
                if ((approve.type === type) && (id !== approve.id)) {
                  approve.status = '1';
                }
              });
            }
            this.closeDialog();
          } else {
            this.$message.error(`保存失败：${result.comment}`);
          }
        }).catch((error) => {
          this.closeDialog();
          console.log(JSON.stringify(error));
        });
      }
    },
    // 监听审批翻页
    changeApprovePage (currentPage) {
      const params = this.makeSearch();
      params.pageNum = currentPage;
      this.loadingApproves = true;
      ManApi.getApproveList(params).then((result) => {
        if (!result.status) {
          this.approveList = result.obj.records;
          this.approveListTotal = result.obj.totalNum;
          this.currentPage = currentPage;
        } else {
          this.approveList = [];
          this.approveListTotal = 1;
          this.currentPage = 1;
          this.$message.error(result.comment);
        }
        this.loadingApproves = false;
      }).catch((error) => {
        this.loadingApproves = false;
        console.log(JSON.stringify(error));
      });
    },
  },
  beforeRouteEnter (to, from, next) {
    next((vm) => {
      console.log('99');
      // 类型列表
      ComApi.getTypes({ orderType: 'approve' }).then((tyspList) => {
        vm.typeSelect = tyspList;
        vm.typeSelectAll = [{ name: '全部', value: null }].concat(tyspList);
      });
      // 采购员列表
      ComApi.getEmployees({ roleId: '0004' }).then((buyerSelect) => {
        vm.buyerSelect = buyerSelect;
      });
    });
  },
  created () {
  },
  mounted () {
    ManApi.getApproveList().then((result) => {
      if (!result.status) {
        this.approveList = result.obj.records;
        this.approveListTotal = result.obj.totalNum;
      } else {
        this.$message.error(result.comment);
      }
      this.loadingApproves = false;
    }).catch((error) => {
      this.loadingApproves = false;
      console.log(JSON.stringify(error));
    });
  }
};
</script>

<style lang="sass">
@import "../../../styles/utils"
$SEARCHHEIGHT: 56px
$PAGEHEIGHT: 56px
.cp-manage-approve
  .ae-search
    height: $SEARCHHEIGHT
    overflow-x: auto
    overflow-y: hidden
    padding: 12px 0 12px 16px
    .el-form-item
      margin-right: 14px
    .el-form-item__label
      padding-right: 6px
  .ae-table
    position: absolute
    top: $SEARCHHEIGHT
    bottom: $PAGEHEIGHT
    left: 16px
    right: 16px
    overflow: auto
    table
      &::before
        display: none
      .icon-act
        font-size: 16px
        margin-left: 3px
        margin-right: 3px
        cursor: pointer
        &.disabled
          cursor: not-allowed
  .ae-pagination
    position: absolute
    bottom: 12px
    left: 0
    right: 0
    text-align: center
  .el-dialog__body
    padding: 24px 36px 28px 40px
  .ae-pop-show
    padding: 4px 16px
    .el-row
      margin-bottom: 12px
      &:nth-child(odd)
        background: #f5f5f5
      &:nth-child(even)
        background: beige
    strong
      display: inline-block
      font-weight: 400
      margin-right: 8px
  .ae-pop-form
    .el-form-item
      width: 100%
      margin-right: 0
    .el-form-item__content
      width: calc(100% - 72px)
      .el-date-editor.el-input, .el-date-editor.el-input__inner
        width: 100%
    .el-form-item__label
      text-align: left
    .el-select
      width: 100%
    .special-label
      label
        text-align: right
    .span-required:before
      position: absolute
      top: 50%
      left: -10px
      transform: translateY(-50%)
      content: '*';
      color: #f56c6c;
  .ae-approve-row
    margin-bottom: 16px
  .ae-approve-reset
    margin-top: -8px
    margin-bottom: 16px
</style>

